package com.wfcm.controller;

import com.alibaba.fastjson.JSONObject;
import com.wfcm.annotation.IgnoreSign;
import com.wfcm.annotation.IgnoreToken;
import com.wfcm.entity.*;
import com.wfcm.exception.WFCMException;
import com.wfcm.service.*;
import com.wfcm.utils.*;
import com.wfcm.wxPay.MD5Util;
import com.wfcm.wxPay.ResponseHandler;
import com.wfcm.wxPay.WXOrderQuery;
import com.wfcm.wxPay.WXPayUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.runtime.directive.Foreach;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/myCourse")
@ResponseBody
public class MyCourseController {

	private Logger log = LoggerFactory.getLogger(MyCourseController.class);
	@Autowired
	private WfGoodsOrderService goodsOrderService;
	@Autowired
	private WfGoodsOrderRelationService goodsOrderRelationService ;
	@Autowired
	private WfCoinLogService coinLogService ;
	@Autowired
	private WfMemberCouponsService memberCouponsService ;
	@Autowired
	private WfCourseChapterService courseChapterService;
	@Autowired
	private WfCourseInfoService courseInfoService;
	@Autowired
	private WfVipCardService vipCardService;
	@Autowired
	private WfActivityService activityService;
	@Autowired
	private WfMemberInvitationService invitationService;
	@Autowired
	private WfBillService billService;
	@Autowired
	private WfShoppingCartService shoppingCartService;
	@Autowired
	private WfMemberNewGoldLogService memberNewGoldLogService ;
	@Autowired
	private WfMemberGoldLogService memberGoldLogService ;
	@Autowired
	private WfMemberGiveCoinLogService memberGiveCoinLogService ;
	@Autowired
	private WfRechargeService rechargeService ;
	@Autowired
	private WfMemberRechargeOrderService memberRechargeOrderService;
	@Autowired
	private WfMemberService memberService;
	@Autowired
	private WfCollectionService collectionService;
	@Autowired
	private WfCourseGiftService courseGiftService;
	@Autowired
	private WfCollageOrderService collageOrderService;
	@Autowired
	private DistributionService distributionService;
	@Autowired
	private WfLuckyService luckyService;
	@Autowired
	private WfLuckyCodeService luckyCodeService;
	@Autowired
	private WfNewMessageService newMessageService;
	@Autowired
	private RecordService recordService;
	@Autowired
	private WfMyCourseSortService myCourseSortService;

	/**
	 * 已购课程增加分栏
	 */
	@RequestMapping("/addSort")
	@ResponseBody
	public R addSort(HttpServletRequest req,String sortName) {

		Integer uid = ISsoLoginHelper.confirm(req);
		WfMyCourseSort myCourseSort = new WfMyCourseSort();
		myCourseSort.setSortName(sortName);
		myCourseSort.setUserId(uid);
		myCourseSortService.save(myCourseSort);
		return R.ok();
	}

	/**
	 * 删除已购课程分栏
	 */
	@RequestMapping("/delSort")
	@ResponseBody
	public R delSort(Integer id) {

		myCourseSortService.delete(id);
		return R.ok();
	}
	/**
	 * 删除分栏课程
	 */
	@RequestMapping("/delCourse")
	@ResponseBody
	public R delCourse(String ids) {
		String[] idList = ids.split(",");
		myCourseSortService.deleteBatch(idList);
		return R.ok();
	}


	/**
	 * 修改已购课程分栏
	 */
	@RequestMapping("/updateSort")
	@ResponseBody
	public R updateSort(HttpServletRequest req,Integer id,String sortName) {
		WfMyCourseSort myCourseSort = new WfMyCourseSort();
		myCourseSort.setSortName(sortName);
		myCourseSort.setId(id);
		myCourseSortService.update(myCourseSort);
		return R.ok();
	}

	/**
	 * 查询已购课程分栏
	 */
	@RequestMapping("/selSort")
	@ResponseBody
	public R selSort(HttpServletRequest req) {
		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);
		map.put("uid",uid);
		List<WfMyCourseSort> myCourseSortList= myCourseSortService.queryList(map);
		return R.ok().put("myCourseSortList",myCourseSortList);
	}


	/**
	 * 查询分栏内已购课程
	 */
	@RequestMapping("/courseInSort")
	@ResponseBody
	public R courseInSort(HttpServletRequest req,Integer sortId) {
		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);
		map.put("uid",uid);
		map.put("sortId",sortId);
		List<WfCourseInSort> courseInSortList= myCourseSortService.queryCourseInSort(map);
		return R.ok().put("courseInSortList",courseInSortList);
	}

	/**
	 * 分栏添加课程
	 */
	@RequestMapping("/sortAddCourse")
	@ResponseBody
	public R sortAddCourse(HttpServletRequest req,Integer sortId,String goodsId,String goodsSort) {
		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);
		map.put("uid",uid);
		map.put("sortId",sortId);
		List<String> idList = strToList(goodsId);
		List<String> sortList = strToList(goodsSort);
		for(int i=0; i<idList.size(); i++){
			WfMyCourseSort myCourseSort = new WfMyCourseSort();
			myCourseSort.setUserId(uid);
			myCourseSort.setGoodsId(Integer.valueOf(idList.get(i)));
			myCourseSort.setGoodsSort(Integer.valueOf(sortList.get(i)));
			myCourseSortService.save(myCourseSort);
		}
		return R.ok();
	}

	public static List strToList(String type){
		String[] typeArr = type.split(",");
		List<String> typeList1 = Arrays.asList(typeArr);//数组转为list
		List<String> typeList = new ArrayList(typeList1);
		return typeList;
	}

	/**
	 * 正在用：已购课程
	 */
	@RequestMapping("/myCourseList")
	@ResponseBody
	public R myCourseList(HttpServletRequest req) {

		Map<String,Object> map =new  HashMap<String,Object>();
		Integer uid = ISsoLoginHelper.confirm(req);
		map.put("uid", uid);
		map.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		//获取已购课程个数
		List<WfCourseInfoEntity> courseInfoList = new ArrayList();//课程

		List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map);//根据订单号获取其中所有课程
		for(int j=0 ; j<courseList.size(); j++) {
			WfGoodsOrderRelationEntity gor = courseList.get(j);
			//1.课程 2.章节3.vip卡 4商品
			if(1 == gor.getGoodssort()) {
				WfCourseInfoEntity  courseInfoEntity = courseInfoService.querySimpleObject(gor.getGoodsid());
				if(null != courseInfoEntity) {
					courseInfoList.add(courseInfoEntity);
				}
			}else if(2 == gor.getGoodssort()){
				WfCourseChapterEntity  courseChapterEntity = courseChapterService.querySimpleObject(gor.getGoodsid());
				WfCourseInfoEntity  courseInfoEntity = courseInfoService.querySimpleObject(courseChapterEntity.getCourseid());
				Map<String,Object> map1 =new  HashMap<String,Object>();
				map1.put("courseId", courseInfoEntity.getId());
				map1.put("chapterType", 1);//免费
				List<WfCourseChapterEntity>  courseChapterFreeList = courseChapterService.queryFreeObject(map1);
				if(null == courseChapterFreeList) {
					courseChapterFreeList = new ArrayList<WfCourseChapterEntity>();
				}
				courseChapterFreeList.add(courseChapterEntity);
				courseInfoEntity.setCourseChapterList(courseChapterFreeList);
				if(null != courseInfoEntity) {
					courseInfoList.add(courseInfoEntity);
				}
			}
		}

		return R.ok().put("courseInfoList", courseInfoList);
	}
	/**
	 * 课程包中课程
	 */
	@RequestMapping("/vipCard")
	@ResponseBody
	@IgnoreToken
	public R vipCard(HttpServletRequest req) {

		Map<String,Object> map =new  HashMap<String,Object>();
		String vipCardId = req.getParameter("vipCardId");
		map.put("vipCardId", vipCardId);

		//查询课程包中课程
		List<WfVipCardEntity> courseList = vipCardService.queryCourseList(map);

		Map<String,Object> resultMap =new  HashMap<String,Object>();
		resultMap.put("courseList", courseList);

		return R.ok(resultMap);
	}

	/**
	 * 课程中章节简要
	 */
	@RequestMapping("/courseChapter")
	@ResponseBody
	@IgnoreToken
	public R courseChapter(HttpServletRequest req) {

		Map<String,Object> map1 =new  HashMap<String,Object>();
		String courseId = req.getParameter("courseId");
		map1.put("courseId", courseId);
		map1.put("buy", courseId);
		//查询课程包中课程 querySimpleChapter
		List<WfCourseChapterEntity> myCourseChapterList= courseChapterService.querySimpleChapter(map1);
		Map<String,Object> resultMap =new  HashMap<String,Object>();
		resultMap.put("courseChapterList", myCourseChapterList);

		return R.ok(resultMap);
	}

	/**
	 * 课程中章节简要
	 */
	@RequestMapping("/freeCourseChapter")
	@ResponseBody
	public R freeCreeChapter(HttpServletRequest req) {

		Map<String,Object> map1 =new  HashMap<String,Object>();
		String courseId = req.getParameter("courseId");
		map1.put("courseId", courseId);
		//查询课程包中课程 querySimpleChapter
		List<WfCourseChapterEntity> myCourseChapterList= courseChapterService.querySimpleChapter(map1);

		List<WfCourseChapterEntity> courseChapterList = new ArrayList<WfCourseChapterEntity>();//仅展示课程中已买的章节
		List<WfGoodsOrderRelationEntity> chapterList = new ArrayList<WfGoodsOrderRelationEntity>();//所有的已买章节

		int access = -1;//标识
		Integer uid = ISsoLoginHelper.confirm(req);
		//获取已购课程个数
		map1.put("uid", uid);
		map1.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map1);//根据uid获取订单
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			int cId = Integer.parseInt(courseId);//页面传来的课程参数值
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			Map<String,Object> map2 =new  HashMap<String,Object>();
			map2.put("orderCode",goodsOrderEntity.getOrdercode());
			map2.put("goodsSort",1);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程
			for(int j=0 ; j<courseList.size(); j++) {
				if(cId == courseList.get(j).getGoodsid()) {
					access = 1;
					break;//跳出课程循环
				}
			}
			if(access == 1) {
				break;//跳出订单循环
			}
			map2.put("goodsSort",3);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> vipList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程包
			for(int m=0 ; m<vipList.size(); m++) {
				Integer vcId = vipList.get(m).getGoodsid();
				Map<String,Object> map3 =new  HashMap<String,Object>();
				map3.put("vipCardId",vcId);
				List<WfVipCardEntity> vipCardList = vipCardService.queryCourseList(map3);//获取课程包中个课程
				for(int k=0; k<vipCardList.size(); k++) {
					if(cId == vipCardList.get(k).getCardCourseRelationList().get(0).getCourseInfoEntity().getId()) {
						access = 1;
						break;//若课程已买，则跳出课程包循环
					}
				}
			}
			if(access == 1) {
				break;//跳出订单循环
			}
			map2.put("goodsSort",2);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> chapterList1 =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的章节
			for(int j=0 ; j<chapterList1.size(); j++) {
				chapterList.add(chapterList1.get(j));
			}
		}
		//判断课程中的章节是否购买
		if(access != 1) {//若未买过此课程，则判断已买的章节
			for(int n=0 ; n<chapterList.size(); n++) {
				WfGoodsOrderRelationEntity gor = chapterList.get(n);
				int flag = -1;//标识
				for(int k=0; k<myCourseChapterList.size(); k++) {
					int id = myCourseChapterList.get(k).getId();
					int goodsid = gor.getGoodsid();
					if( id == goodsid) {
						flag = k;
						break;
					}
				}
				if(flag != -1) {//若已购买则保留
					courseChapterList.add(myCourseChapterList.get(flag));
				}
			}
		}
		Map<String,Object> map3 =new  HashMap<String,Object>();
		map3.put("courseId", courseId);
		map3.put("chapterType", 1);//免费
		List<WfCourseChapterEntity>  courseChapterFreeList = courseChapterService.queryFreeObject(map3);

		Map<String,Object> resultMap =new  HashMap<String,Object>();
		if(access == 1) {
			/*for(int i=0; i<courseChapterFreeList.size(); i++) {
				myCourseChapterList.add(courseChapterFreeList.get(i));
			}*/
			resultMap.put("courseChapterList", myCourseChapterList);
		}else {
			for(int i=0; i<courseChapterFreeList.size(); i++) {
				courseChapterList.add(courseChapterFreeList.get(i));
			}
			resultMap.put("courseChapterList", courseChapterList);
		}
		return R.ok(resultMap);
	}

}
